//引入koa
const Koa = require('koa')
const app = new Koa()
const session = require('koa-session')

const bodyParser = require('koa-bodyparser')
app.use(bodyParser())

const router = require('koa-router')
const views = require('koa-views')
const query = require('./mysql')
app.keys = ['some secret hurr']

const CONFIG = {
    key: 'zhj:sess',   //cookie key (default is koa:sess)
    maxAge: 86400000,  // cookie的过期时间 1天
    overwrite: false,  //是否可以overwrite    (默认default true)
    httpOnly: false,   //cookie是否只有服务器端可以访问 httpOnly or not (default true)
    signed: false,     //签名默认true
    rolling: false,    //在每次请求时强行设置cookie，这将重置cookie过期时间（默认：false）
    renew: false,      //cookie将在到期前重新设置（默认：false）
}


app.use(session(CONFIG, app))
app.use(views(__dirname + '/views', {
    extension: 'ejs'
}
))

app.use(async (ctx, next) => {
    await next()
    const referer = ctx.request.header.referer
    console.log(referer);
    
})

app.use(async (ctx,next) => {
    await next()
    //参数出现在HTML内容或属性浏览器会拦截
    ctx.set('X-XSS-Protection',0)
    ctx.set('X-FRAME-OPTION','DENY')
    await ctx.render('index',{
        from: ctx.query.from,
        username: ctx.session.username,
        text:res[0].text,
    })
})



router.get('/login', async (ctx)=>{
    await ctx.render('login')
})

const encryptPassword = require('./password')


////SQL可注入写法

// router.post('/login', async (ctx)=>{
//     const {password} = ctx.request.body
//     const {username} = ctx.request.body

//     //可注入写法
//     let sql=`
//     select * from test.user
//     where username = '${username}' and password = '${password}'
//     `
//     console.log('sql',sql);
//     res = await query(sql)
//     console.log('db',res);
//     if(res.length !== 0){
//         ctx.redirect('/?from=china')
//         ctx.session.username = ctx.request.body.username
//     }else{
//         ctx.body = {
//             code: 500,
//             data: '登录失败'
//         }        
//     }    
// })


////SQL不可注入写法

// router.post('/login', async (ctx)=>{
//     const {password} = ctx.request.body
//     const {username} = ctx.request.body

//     //不可注入写法
//     let sql=`
//     select * from test.user
//     where username = ？ and password = ？
//     `
//     console.log('sql',sql);
//     res = await query(sql,[username,password])
//     console.log('db',res);
//     if(res.length !== 0){
//         ctx.redirect('/?from=china')
//         ctx.session.username = ctx.request.body.username
//     }else{
//         ctx.body = {
//             code: 500,
//             data: '登录失败'
//         }        
//     }    
// })

//密码加密后的写法
router.post('/login', async (ctx)=>{
    const {password} = ctx.request.body
    const {username} = ctx.request.body
   
    let sql=`
    select * from test.user
    where username = ？ 
    --and password = ？
    `
    console.log('sql',sql);
    res = await query(sql,[username])
    console.log('db',res);
    if(res.length !== 0 && res[0].salt === ''){
        console.log('no salt...');
        sql=`
        update test.user set salt = ?,password = ? where username = ?
        `
        const salt = Math.random()*999999 + new Date().getTime()
        const password = encryptPassword(salt,password)
        res = await query(sql,[salt,password,username])
        ctx.session.username = ctx.request.body.username
        ctx.redirect('/?from=china')
    }else{
        console.log('has salt...');
        if(encryptPassword(res[0].salt,password) === res[0].password){
            ctx.session.username = ctx.request.body.username
            ctx.redirect('/?from=china')
        }
        
    }   
})

//白名单
const xss=require('xss')
let html = xss('<h1 id="title">XSS Demo</h1><script>alert("xss");</script>')


router.get('/', async (ctx)=>{
    res = await query(`select * from test.text`)
    await ctx.render('index',{
        from: html,
        username: ctx.session.username,
        text:res[0].text,
    })    
})


function escape(str){
    str=str.replace(/&/g,'&amp;')
    str =str.replace(/</g,'&lt;')
    str=str.replace(/>/g,'&gt;')
    str =str.replace(/"/g,'&quto;')
    str =str.replace(/'/g,'&#39;')
    str =str.replace(/`/g,'&#96;')
    str =str.replace(/\//g,'&#x2F;')
    return str
}



router.post('/updateText', async (ctx)=>{
    text = ctx.request.body.text
    res= await query(`REPLACE INTO test.text (id, text) set text = '${text}' where username = '${ctx.session.username}'`)
    console.log('mysql:',ctx.request.body);
    ctx.redirect('/')
    
})

app.use(router.routes())
app.use(router.allowedMethods())

module.exports = app